"""
Case Type   : HTAP行列融合特性
Case Name   : 表中有索引时，行列转换后，开启开关，查看查询计划
Create At   : 2025/1/13
Owner       : ningyali
Description :
    1.建表并创建索引
    2.插入数据
    3.行列转换
    4.开启enable_imcsscan，explain和查询
    5.关闭enable_imcsscan，explain和查询
    6.插入数据
    7.查询
    8.清理数据环境
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功
    4.执行成功, 查询计划走imcs scan
    5.执行成功，查询计划不走imcs scan,查询结果与第四步一致
    6.执行成功
    7.查询数据正确
    8.执行成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import macro


class HTAP(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('SingleDbUser')
        self.Constant = Constant()
        self.common = Common()
        self.t_name = 't_htap_single_0144'

    def test_trans(self):
        text = '----step1:建表并创建索引; expect:执行成功----'
        self.log.info(text)
        sql = f'drop table if exists {self.t_name} cascade;' \
              f'create table {self.t_name}(' \
              f'    c1 integer,' \
              f'    c2 varchar(30),' \
              f'    c3 char(30));' \
              f'create unique index idx_{self.t_name} ' \
              f'on {self.t_name}(c1,c2);'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        expect_res = r'CREATE TABLE\s+CREATE INDEX'
        self.assertRegex(sql_res, expect_res, f'执行失败:{text}')

        text = '----step2:插入数据; expect:执行成功----'
        self.log.info(text)
        sql = f'insert into {self.t_name} values (' \
              f'generate_series(1, 100000),' \
              f'generate_series(1, 100000)||\'c2\',' \
              f'generate_series(1, 100000)||\'c3\');' \
              f'\\d+'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        self.assertIn('INSERT 0 100000', sql_res, f'执行失败:{text}')

        text = '----step3:行列转换; expect:执行成功----'
        self.log.info(text)
        sql = f'alter table {self.t_name} imcstored;'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        self.assertIn('ALTER TABLE', sql_res, f'执行失败:{text}')

        text = '----step4:开启enable_imcsscan，explain和查询; ' \
               'expect:执行成功, 查询计划走imcs scan----'
        self.log.info(text)
        q_sql = f'with \n' \
                f'  cte_1 as (select c1/2 as c1,c2 from {self.t_name} ' \
                f'where c1%2=0),\n' \
                f'  cte_2 as (select c1,c3 from {self.t_name} ' \
                f'where c3 like \'%9999c3%\')\n' \
                f'select * from cte_1 a join cte_2 b on a.c1=b.c1 order by a.c1'
        sql = f'set enable_bitmapscan=off;' \
              f'set enable_seqscan=off;' \
              f'set enable_indexscan=off;' \
              f'set enable_imcsscan=on;' \
              f'explain (costs false) {q_sql};' \
              f'{q_sql}'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        rows1, _ = self.common.parse_sql_query_res(sql_res)
        expect = [['9999', '19998c2', '9999', '9999c3'],
                  ['19999', '39998c2', '19999', '19999c3'],
                  ['29999', '59998c2', '29999', '29999c3'],
                  ['39999', '79998c2', '39999', '39999c3'],
                  ['49999', '99998c2', '49999', '49999c3']]
        self.assertEqual(sql_res.count('IMCStore Scan'), 2, f'执行失败:{text}')
        self.assertEqual(expect, rows1[-5:], f'执行失败:{text}')

        text = '----step5:关闭enable_imcsscan，explain和查询; ' \
               'expect:执行成功，查询计划不走imcs scan,查询结果与第四步一致----'
        self.log.info(text)
        sql = f'set enable_bitmapscan=off;' \
              f'set enable_seqscan=off;' \
              f'set enable_indexscan=on;' \
              f'set enable_imcsscan=off;' \
              f'explain (costs false) {q_sql};' \
              f'{q_sql}'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        rows2, _ = self.common.parse_sql_query_res(sql_res)
        self.assertNotIn('IMCStore Scan', sql_res, f'执行失败:{text}')
        self.assertEqual(rows1[-5:], rows2[-5:], f'执行失败:{text}')

        text = '----step6:插入数据; expect:执行成功----'
        self.log.info(text)
        sql = f'insert into {self.t_name} values (' \
              f'generate_series(100001, 200000),' \
              f'generate_series(100001, 200000)||\'c2\',' \
              f'generate_series(100001, 200000)||\'c3\');' \
              f'\\d+'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        self.assertIn('INSERT 0 100000', sql_res, f'执行失败:{text}')

        text = '----step7:开启enable_imcsscan，explain和查询; ' \
               'expect:执行成功, 查询计划走imcs scan----'
        self.log.info(text)
        sql = f'set enable_bitmapscan=off;' \
              f'set enable_seqscan=off;' \
              f'set enable_indexscan=off;' \
              f'set enable_imcsscan=on;' \
              f'explain (costs false) {q_sql};' \
              f'{q_sql}'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        rows1, _ = self.common.parse_sql_query_res(sql_res)
        expect.extend([['59999', '119998c2', '59999', '59999c3'],
                       ['69999', '139998c2', '69999', '69999c3'],
                       ['79999', '159998c2', '79999', '79999c3'],
                       ['89999', '179998c2', '89999', '89999c3'],
                       ['99999', '199998c2', '99999', '99999c3']])
        self.assertEqual(sql_res.count('IMCStore Scan'), 2, f'执行失败:{text}')
        self.assertEqual(expect, rows1[-10:], f'执行失败:{text}')

    def tearDown(self):
        text = '----step8:清理环境;expect:执行成功----'
        self.log.info(text)
        sql = f'drop table if exists {self.t_name} cascade;'
        sql_res = self.pri_sh.execut_db_sql(
            sql, env_path=macro.SINGLE_DB_ENV_PATH)
        self.assertIn('DROP TABLE', sql_res, f'修改表失败:{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
